import { PropsWithChildren, ReactNode, useState } from "react";
import * as RadixCollapsible from "@radix-ui/react-collapsible";
import { AnimatePresence, m } from "framer-motion";
import { clsxm } from "../helpers";

type CollapseProps = PropsWithChildren<{
  trigger: ReactNode;
  className?: string;
  contentClassName?: string;
}>;
export function Collapse(props: CollapseProps) {
  const { children, trigger, className, contentClassName } = props;
  const [open, setOpen] = useState(false);
  return (
    <RadixCollapsible.Root
      open={open}
      onOpenChange={setOpen}
      className={className}
    >
      <RadixCollapsible.Trigger>{trigger}</RadixCollapsible.Trigger>
      <AnimatePresence>
        {open && (
          <RadixCollapsible.Content asChild forceMount>
            <m.div
              className={clsxm("overflow-hidden", contentClassName)}
              initial={{ height: 0 }}
              animate={{ height: "auto" }}
              exit={{ height: 0 }}
            >
              {children}
            </m.div>
          </RadixCollapsible.Content>
        )}
      </AnimatePresence>
    </RadixCollapsible.Root>
  );
}
